/*
* Author: honrun
*/
#include "CSU8RP3216.h"
#include <stdint.h>
#include "DevicesTimer.h"
#include "DevicesTime.h"


/* 定时器的溢出次数，以此为计时标准 */
volatile uint32_t g_lTimerHigh = 0;


/* 单位us */
uint32_t lTimeGetStamp(void)
{
    volatile uint32_t lUNIXTimeStamp = 0, lTimeHighFirst = 0, lTimeHighSecond = 1;
    volatile uint8_t ucTimerCntHighFirst = 0, ucTimerCntHighSecond = 0;
    volatile uint8_t ucTimerCntLow = 0;

    /* 保证不会读取到进位时的值，以造成时间错乱 */
    while((lTimeHighFirst != lTimeHighSecond) || (ucTimerCntHighFirst != ucTimerCntHighSecond))
    {
        lTimeHighFirst = g_lTimerHigh;
        ucTimerCntHighFirst = TM4CNTH & 0x0F;

        ucTimerCntLow  = TM4CNT;

        lTimeHighSecond = g_lTimerHigh;
        ucTimerCntHighSecond = TM4CNTH & 0x0F;
    }

    lUNIXTimeStamp = lTimeHighFirst + ((uint32_t)ucTimerCntHighFirst << 4) + ucTimerCntLow;

    return lUNIXTimeStamp;
}
